package cn.stylefeng.guns.modular.demo.service;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.guns.dao.*;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.entity.yaode.GaiaProductBusiness;
import cn.stylefeng.guns.dao.mapper.SalesStockBatchMapper;
import cn.stylefeng.guns.dao.mapper.WholesaleSalesRecordBatchMapper;
import cn.stylefeng.guns.dao.mapper.WholesaleSalesRecordMapper;
import cn.stylefeng.guns.dao.service.*;
import cn.stylefeng.guns.modular.demo.enums.SaleStockTypeEnum;
import cn.stylefeng.guns.util.RebateDateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TestBizService {

    @Resource
    private ITestSetService testSetService;
    @Resource
    private ITestSetStoreService testSetStoreService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IStoreService storeService;
    @Resource
    private ISaleStockService saleStockService;
    @Resource
    private IGaiaProductBusinessService gaiaProductBusinessService;
    @Resource
    private IWholesaleSalesRecordService wholesaleSalesRecordService;
    @Resource
    private IWholesaleSalesRecordBatchService wholesaleSalesRecordBatchService;
    @Resource
    private WholesaleSalesRecordMapper wholesaleSalesRecordMapper;
    private static final DateTimeFormatter SIMPLE_DATE_FORMAT1 = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final Long DAY_TIME = 24 * 3600 * 1000L;
    @Resource
    private IGaiaBatchInfoService gaiaBatchInfoService;
    @Resource
    private ISupplierService supplierService;

    @Resource
    private WholesaleSalesRecordBatchMapper wholesaleSalesRecordBatchMapper;
    @Resource
    private SalesStockBatchMapper salesStockBatchMapper;

    /**
     * 逆向退货
     *
     * @param timeParam
     */
    @Transactional(rollbackFor = Exception.class)
    public void generateSingleTestDataReturn(String timeParam) {
        //查询需要退货的库存
        List<WholesaleSalesRecord> wholesaleSalesRecords = wholesaleSalesRecordMapper.findReturn();
        if (CollectionUtils.isEmpty(wholesaleSalesRecords)) {
            log.error("没有需要退货的数据");
            return;
        }
        LocalDate date = LocalDate.parse(timeParam, SIMPLE_DATE_FORMAT1);
        LocalTime localTimeOpen = LocalTime.of(0, 0);
        LocalDateTime localDateTime = LocalDateTime.of(date, localTimeOpen);
        long saleTime = localDateTime.toEpochSecond(ZonedDateTime.now().getOffset()) * 1000;
        for (WholesaleSalesRecord wholesaleSalesRecord : wholesaleSalesRecords) {
            Integer usedNum = wholesaleSalesRecord.getUsedNum();
            Integer totalNum = wholesaleSalesRecord.getTotalNum();
            String batchNo = wholesaleSalesRecord.getBatchNo();
            String proCode = wholesaleSalesRecord.getProCode();

            Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, proCode));
            if (Objects.isNull(goods)) {
                log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
                return;
            }
            usedNum = Objects.isNull(usedNum) ? 0 : usedNum;
            totalNum = Objects.isNull(totalNum) ? 0 : totalNum;
            Integer returningNum = usedNum - totalNum;
            wholesaleSalesRecord.setUsedNum(usedNum - returningNum);
            //更新使用量
            wholesaleSalesRecordService.updateById(wholesaleSalesRecord);
            //退发货数据和销售数据
            returnStore(batchNo, goods, saleTime, totalNum);
        }

    }


    /**
     * 找到库存多一点的门店退货
     *
     * @param batchNo
     * @param goods
     * @param saleTime
     * @param returningNum 需要退货的数量
     */
    private void returnStore(String batchNo, Goods goods, Long saleTime, Integer returningNum) {
//        List<WholesaleSalesRecordBatch> salesStockBatches = wholesaleSalesRecordBatchMapper.selectList(Wrappers.<WholesaleSalesRecordBatch>query()
//                .eq("batch_no", batchNo)
//                .eq("pro_code", goods.getCommodityCode())
//                .orderByDesc("total_num -used_num"));
//        if (CollectionUtils.isEmpty(salesStockBatches)) {
//            log.error("[测试数据错误]没有库存数据，无法退货batchNo ={},totalNum={}", batchNo, returningNum);
//            return;
//        }
//        //先从库存里面退，如果不够，再从发货记录退
//        for (WholesaleSalesRecordBatch wholesaleSalesRecordBatch : salesStockBatches) {
//            Integer usedNum = wholesaleSalesRecordBatch.getUsedNum();
//            Integer totalNum = wholesaleSalesRecordBatch.getTotalNum();
//            if (returningNum <= 0) {
//                break;
//            }
//            int localNum = 0;
//            //能退货的数量
//            int canReturnedAmount = totalNum - usedNum;
//            //退货数量
//            if (returningNum < canReturnedAmount) {
//                localNum = returningNum;
//                returningNum = 0;
//            } else {
//                localNum = canReturnedAmount;
//                returningNum = returningNum - canReturnedAmount;
//            }
//            //库存退货
//            wholesaleSalesRecordBatch.setTotalNum(totalNum - localNum);
//            wholesaleSalesRecordBatchService.updateById(wholesaleSalesRecordBatch);
//        }
        //库存里面的数量够退了 直接返回
//        if (returningNum < 0) {
//            return;
//        }


        //查询连锁的发货记录，测试数据
        List<SaleStock> records = saleStockService.list(Wrappers.<SaleStock>lambdaQuery()
                .eq(SaleStock::getTest, 1)
                .eq(SaleStock::getBatchNo, batchNo)
                .eq(SaleStock::getSaleType, 1)
                .eq(SaleStock::getGoodsId, goods.getGoodsId())
                .eq(SaleStock::getType, "store")
//                    .eq(SaleStock::getGoodsId, proCode)
                .eq(SaleStock::getStoCode, "100")
                .le(SaleStock::getSaleTime, saleTime)
                .orderByDesc(SaleStock::getSaleTime));
        //不需要退货
        if (CollectionUtils.isEmpty(records)) {
            log.error("[测试数据错误]没有库存数据，无法退货batchNo ={},totalNum={}", batchNo, returningNum);
            return;
        }
        for (SaleStock record : records) {
            if (returningNum <= 0) {
                break;
            }
            Integer totalNum = record.getNum();
            //真正退了多少
            Integer localStoreNum = 0;

            //退货数量
            if (returningNum < totalNum) {
                localStoreNum = returningNum;
                returningNum = 0;
            } else {
                returningNum = returningNum - totalNum;
                localStoreNum = totalNum;
            }
            //退货 退门店
            SaleStock saleStock = new SaleStock();
            saleStock.setSaleType(2);
            saleStock.setType(record.getType());
            saleStock.setTest(1);
            saleStock.setNum(localStoreNum);
            saleStock.setStoCode(record.getStoCode());
            saleStock.setPayName(record.getPayName());
            saleStock.setFactoryName(record.getFactoryName());
            saleStock.setAmountReceivable(goods.getPrice().multiply(new BigDecimal(localStoreNum)));
            saleStock.setCanRebate(0);
            saleStock.setBatchNo(batchNo);
            saleStock.setSaleTime(saleTime);
            saleStock.setGoodsId(record.getGoodsId());
            saleStock.setSupplierId(record.getSupplierId());
            saleStock.setGssdBillNo(record.getGssdBillNo());
            saleStock.setPrice(record.getPrice());
            saleStock.setProductionEnterprise(record.getProductionEnterprise());
            saleStock.setHolder(record.getHolder());
            saleStock.setReceivablePrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setAmountReceivable(goods.getPrice().multiply(new BigDecimal(localStoreNum)));
            saleStock.setOriginalPrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setPoId(record.getPoId());
            saleStock.setBillNo(record.getBillNo());
            saleStockService.save(saleStock);
            List<SaleStock> list = saleStockService.list(Wrappers.<SaleStock>lambdaQuery()
                    .eq(SaleStock::getPoId, record.getPoId())
                    .eq(SaleStock::getBatchNo, batchNo)
                    .notIn(SaleStock::getStoCode, Lists.newArrayList("100")));
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                log.warn("没有连锁门店的发货记录，无法退货，batchNo ={},totalNum={}", batchNo, returningNum);
                continue;
            }
            if (list.size() > 1) {
                log.warn("连锁门店的发货记录有多条，无法退货，batchNo ={},totalNum={}", batchNo, returningNum);
                continue;
            }
            SaleStock one = list.get(0);
            //退货
            SaleStock saleStockReturn = new SaleStock();
            saleStockReturn.setSaleType(2);
            saleStockReturn.setType(one.getType());
            saleStockReturn.setTest(1);
            saleStockReturn.setNum(localStoreNum);
            saleStockReturn.setStoCode(one.getStoCode());
            saleStockReturn.setPayName(one.getPayName());
            saleStockReturn.setFactoryName(one.getFactoryName());
            saleStockReturn.setAmountReceivable(goods.getPrice().multiply(new BigDecimal(localStoreNum)));
            saleStockReturn.setCanRebate(0);
            saleStockReturn.setBatchNo(batchNo);
            saleStockReturn.setSaleTime(saleTime);
            saleStockReturn.setGoodsId(one.getGoodsId());
            saleStockReturn.setSupplierId(one.getSupplierId());
            saleStockReturn.setGssdBillNo(one.getGssdBillNo());
            saleStockReturn.setPrice(one.getPrice());
            saleStockReturn.setProductionEnterprise(one.getProductionEnterprise());
            saleStockReturn.setHolder(one.getHolder());
            saleStockReturn.setReceivablePrice(saleStockReturn.getAmountReceivable().doubleValue());
            saleStockReturn.setAmountReceivable(goods.getPrice().multiply(new BigDecimal(localStoreNum)));
            saleStockReturn.setOriginalPrice(saleStockReturn.getAmountReceivable().doubleValue());
            saleStockReturn.setPoId(one.getPoId());
            saleStockReturn.setBillNo(one.getBillNo());
            saleStockService.save(saleStockReturn);
            String stoCode = one.getStoCode();

            //更新门店库存
            WholesaleSalesRecordBatch wholesaleSalesRecordBatch = wholesaleSalesRecordBatchService.getOne(
                    Wrappers.<WholesaleSalesRecordBatch>lambdaQuery()
                            .eq(WholesaleSalesRecordBatch::getBatchNo, batchNo)
                            .eq(WholesaleSalesRecordBatch::getProCode, goods.getCommodityCode())
                            .eq(WholesaleSalesRecordBatch::getDeliverId, one.getPoId()));
            if (Objects.isNull(wholesaleSalesRecordBatch)) {
                log.error("[测试数据错误]没有库存数据，无法退货batchNo ={},totalNum={}", batchNo, returningNum);
                continue;
            }

            Integer localSaleNum = 0;
            //库存数量
            int stockNum = wholesaleSalesRecordBatch.getTotalNum() - wholesaleSalesRecordBatch.getUsedNum();
            //库存够了 就扣库存就够了
            if (localStoreNum < stockNum) {
                wholesaleSalesRecordBatch.setUsedNum(wholesaleSalesRecordBatch.getUsedNum() - localStoreNum);
            } else {
                //库存不够了，就扣库存，然后退销售记录
                localSaleNum = localStoreNum - stockNum;
                wholesaleSalesRecordBatch.setUsedNum(wholesaleSalesRecordBatch.getUsedNum() - localSaleNum);
            }
            wholesaleSalesRecordBatch.setTotalNum(wholesaleSalesRecordBatch.getTotalNum() - localStoreNum);
            wholesaleSalesRecordBatchService.updateById(wholesaleSalesRecordBatch);

            //库存够了就不退了
            if (localSaleNum <= 0) {
                break;
            }
            //查询销售记录
            List<SaleStock> saleRerords = saleStockService.list(Wrappers.<SaleStock>lambdaQuery()
                    .eq(SaleStock::getTest, 1)
                    .eq(SaleStock::getBatchNo, batchNo)
                    .eq(SaleStock::getType, "sale")
                    .eq(SaleStock::getStoCode, stoCode)
                    .le(SaleStock::getSaleTime, saleTime)
                    .orderByDesc(SaleStock::getSaleTime));
            //不需要退货
            if (CollectionUtils.isEmpty(saleRerords)) {
                return;
            }

            for (SaleStock saleRecord : saleRerords) {
                if (localSaleNum <= 0) {
                    break;
                }
                int localNum = 0;
                Integer saleNum = saleRecord.getNum();
                //退货数量
                if (localSaleNum < saleNum) {
                    localNum = localSaleNum;
                    localSaleNum = 0;
                } else {
                    localSaleNum = localSaleNum - saleNum;
                    localNum = saleNum;
                }
                //退货
                SaleStock saleStockSale = new SaleStock();
                saleStockSale.setSaleType(2);
                saleStockSale.setType(saleRecord.getType());
                saleStockSale.setTest(1);
                saleStockSale.setNum(localNum);
                saleStockSale.setStoCode(stoCode);
                saleStockSale.setPayName(saleRecord.getPayName());
                saleStockSale.setFactoryName(saleRecord.getFactoryName());
                saleStockSale.setAmountReceivable(saleRecord.getAmountReceivable());
                saleStockSale.setCanRebate(0);
                saleStockSale.setBatchNo(batchNo);
                saleStockSale.setSaleTime(saleTime);
                saleStockSale.setGoodsId(saleRecord.getGoodsId());
                saleStockSale.setSupplierId(saleRecord.getSupplierId());
                saleStockSale.setGssdBillNo(saleRecord.getGssdBillNo());
                saleStockSale.setPrice(saleRecord.getPrice());
                saleStockSale.setProductionEnterprise(saleRecord.getProductionEnterprise());
                saleStockSale.setHolder(saleRecord.getHolder());
                saleStockSale.setReceivablePrice(saleRecord.getAmountReceivable().doubleValue());
                saleStockSale.setPoId(saleRecord.getPoId());
                saleStockSale.setBillNo(saleRecord.getBillNo());
                saleStockSale.setReceivablePrice(saleRecord.getReceivablePrice());
                saleStockSale.setOriginalPrice(saleRecord.getOriginalPrice());
                saleStockService.save(saleStockSale);
            }
        }
    }

    /**
     * 正向
     *
     * @param timeParam
     */
    public void generateSingleTestData(String timeParam) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        log.info("[generateTestData] begin  time={}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        log.info("[生成测试数据]开始生成正式测试数据，耗时={}", stopwatch.elapsed(TimeUnit.MILLISECONDS));

        List<TestSet> list = testSetService.list();
        if (CollectionUtils.isEmpty(list)) {
            log.error("测试数据设置不存在 跳过");
            return;
        }
        LocalTime localTimeOpen = LocalTime.of(0, 0);
        LocalTime localTimeClose = LocalTime.of(23, 59);
        LocalDate date = LocalDate.parse(timeParam, SIMPLE_DATE_FORMAT1);

        LocalDateTime localDateTime = LocalDateTime.of(date, localTimeOpen);
        long epochSecondOpen = localDateTime.toEpochSecond(ZonedDateTime.now().getOffset()) * 1000;

        LocalDateTime localDateTimeClose = LocalDateTime.of(date, localTimeClose);
        long epochSecondClose = localDateTimeClose.toEpochSecond(ZonedDateTime.now().getOffset()) * 1000;

        long count = saleStockService.count(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getTest, 1)
                .between(SaleStock::getSaleTime, epochSecondOpen, epochSecondClose));
        if (count > 0) {
            log.info("已经生成过数据了，不再生成");
            return;
        }
        List<WholesaleSalesRecord> calList = wholesaleSalesRecordMapper.findUnused();
        log.info("待生成的测试数据 calList ={}", JSON.toJSONString(calList));
        TestSet testSet = list.get(0);
        for (WholesaleSalesRecord wholesaleSalesRecord : calList) {
            try {
                extracted(timeParam, wholesaleSalesRecord, stopwatch, testSet);
            } catch (Exception e) {
                log.info("[generateTestData] error  ={}", JSON.toJSONString(wholesaleSalesRecord), e.getMessage());
                log.error("测试测试数据异常, wholesaleSalesRecord={}，异常={}", JSON.toJSONString(wholesaleSalesRecord), e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public void extracted(String timeParam, WholesaleSalesRecord wholesaleSalesRecord, Stopwatch stopwatch, TestSet testSet) {
        Integer usedNum = wholesaleSalesRecord.getUsedNum();
        Integer totalNum = wholesaleSalesRecord.getTotalNum();
        Long endTime = wholesaleSalesRecord.getEndTime();
        usedNum = Objects.isNull(usedNum) ? 0 : usedNum;
        Integer leftNum = totalNum - usedNum;
        long intervalTime = endTime - RebateDateUtil.getStartOfDayTimestamp(timeParam);

        //待要生成测试数据的数量
        int calNum = 0;
        //间隔超过一天才要分配
        if (intervalTime >= DAY_TIME) {
            //还需要处理几天
            float day = intervalTime / DAY_TIME;
            //每天要处理的数量 平均数 向下去整
            calNum = (int) (leftNum / day);
            //处理完更新使用量
            wholesaleSalesRecord.setUsedNum(usedNum + calNum);
        } else {
            //少于一天的就把余量处理完
            calNum = leftNum;
            wholesaleSalesRecord.setUsedNum(usedNum + calNum);
        }
        wholesaleSalesRecordService.updateById(wholesaleSalesRecord);
        log.info("待更新数据wholesaleSalesRecord ={}", JSON.toJSONString(wholesaleSalesRecord));
        log.info("[生成测试数据]更新库存测试数据，耗时={}", stopwatch.elapsed(TimeUnit.MILLISECONDS));

        generateSingleTestDataV2(testSet, wholesaleSalesRecord.getProCode(), calNum, wholesaleSalesRecord.getBatchNo(), timeParam);
        log.info("[生成测试数据]正式生成库存测试数据，耗时={}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }


    private void handlerSaleData(TestSet testSet, Goods goods, String wmPch, String wmCjrq) {
        List<WholesaleSalesRecordBatch> batchUnused = wholesaleSalesRecordBatchMapper.findBatchUnused();

        log.error("待生成的销售数据 calList ={}", JSON.toJSONString(batchUnused));

//        String time = LocalDate.now().minusDays(1).format(SIMPLE_DATE_FORMAT1);
        for (WholesaleSalesRecordBatch wholesaleSalesRecord : batchUnused) {
            try {
                Integer usedNum = wholesaleSalesRecord.getUsedNum();
                Integer totalNum = wholesaleSalesRecord.getTotalNum();
                Long endTime = wholesaleSalesRecord.getEndTime();
                usedNum = Objects.isNull(usedNum) ? 0 : usedNum;
                Integer leftNum = totalNum - usedNum;
                long intervalTime = endTime - System.currentTimeMillis();
                //待要生成测试数据的数量
                int calNum = 0;
                //间隔超过一天才要分配
                if (intervalTime >= DAY_TIME) {
                    //还需要处理几天
                    float day = intervalTime / DAY_TIME;
                    //每天要处理的数量 平均数 向下去整
                    calNum = (int) (leftNum / day);
                    //处理完更新使用量
                    wholesaleSalesRecord.setUsedNum(usedNum + calNum);
                } else {
                    //少于一天的就把余量处理完
                    calNum = leftNum;
                    wholesaleSalesRecord.setUsedNum(usedNum + calNum);
                }
                wholesaleSalesRecordBatchService.updateById(wholesaleSalesRecord);
                log.info("待更新数据wholesaleSalesRecord ={}", JSON.toJSONString(wholesaleSalesRecord));

                //生成商品销售数据 最大拆成100单售卖
                int[] randomGoods = random(calNum, testSet.getSellNum(), 100);
                ArrayList<SaleStock> saleStockList = Lists.newArrayList();
                for (int gIndex = 0; gIndex < randomGoods.length; gIndex++) {

                    int sellNum = randomGoods[gIndex];
                    if (sellNum == 0) {
                        continue;
                    }
                    String storeCode = wholesaleSalesRecord.getStoreCode();
                    Store store = storeService.getOne(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, storeCode));
                    SaleStock saleStock = saleStockService.getById(wholesaleSalesRecord.getDeliverId());
                    BigDecimal price = goods.getPrice();
                    SaleStock saleStockSale = new SaleStock();
                    saleStockSale.setSaleType(1);
                    saleStockSale.setType("sale");
                    saleStockSale.setTest(1);
                    saleStockSale.setNum(sellNum);
                    saleStockSale.setStoCode(wholesaleSalesRecord.getStoreCode());
                    saleStockSale.setPayName("聚合付");
                    saleStockSale.setFactoryName(goods.getVender());
                    saleStockSale.setAmountReceivable(price.multiply(new BigDecimal(sellNum)));
                    saleStockSale.setCanRebate(0);
                    saleStockSale.setBatchNo(wmPch);
//                P20221001476
                    saleStockSale.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
                    saleStockSale.setGoodsId(goods.getGoodsId());
                    saleStockSale.setSupplierId(saleStock.getSupplierId());
//SD2308131W4K4WI9ZHS6
                    saleStockSale.setGssdBillNo(randomBillNo(wmCjrq));
                    saleStockSale.setPrice(price);
//                saleStock.setSalerId(r.getGssdSalerId());
//                saleStock.setSalerName(r.getBatSalesmanName());
//                saleStock.setCashier(r.getGssdSalerId());

                    saleStockSale.setProductionEnterprise(saleStock.getProductionEnterprise());
                    saleStockSale.setHolder(saleStock.getHolder());
                    saleStockSale.setReceivablePrice(saleStockSale.getAmountReceivable().doubleValue());
                    saleStockSale.setOriginalPrice(saleStockSale.getAmountReceivable().doubleValue());

                    saleStockList.add(saleStockSale);
                }
                log.info("[生成测试数据],生成的测试数据 saleStockList={}", JSON.toJSONString(saleStockList));
                saleStockService.saveBatch(saleStockList);

//                generateSingleTestData(testSet, wholesaleSalesRecord.getProCode(), calNum, wholesaleSalesRecord.getBatchNo(), timeParam);
            } catch (Exception e) {
                log.error("测试测试数据异常, wholesaleSalesRecord={}，异常={}", JSON.toJSONString(wholesaleSalesRecord), e.getMessage());
                e.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) {
//        LocalDate date = LocalDate.parse("20240528", SIMPLE_DATE_FORMAT1);
//        LocalTime localTimeOpen = LocalTime.of(0, 0);
//        LocalDateTime localDateTime = LocalDateTime.of(date, localTimeOpen);
//        long saleTime = localDateTime.toEpochSecond(ZonedDateTime.now().getOffset()) * 1000;
//        System.out.println(saleTime);
//    }


    /**
     * 生成测试数据
     *
     * @param testSet
     */
    public void generateSingleTestData(TestSet testSet, String proCode, Integer num, String wmPch, String wmCjrq) {
        if (Objects.equals(num, 0)) {
            return;
        }


        String testSetId = testSet.getTestSetId();

        GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessService.getOne(Wrappers.<GaiaProductBusiness>lambdaQuery().eq(GaiaProductBusiness::getProSelfCode, proCode));
        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, proCode));
        if (Objects.isNull(goods)) {
            log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
            return;
        }
        BigDecimal price = null;
        Double proHyj = gaiaProductBusiness.getProHyj();
        if (Objects.nonNull(proHyj)) {
            price = BigDecimal.valueOf(proHyj);
        } else {
            price = new BigDecimal(0);
        }

        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery()
                .eq(GaiaBatchInfo::getBatBatch, wmPch));
        if (Objects.isNull(gaiaBatchInfo)) {
            log.info("批次数据有问题gaiaBatchInfo={}", JSON.toJSONString(gaiaBatchInfo));
            return;
        }
        String batSupplierCode = gaiaBatchInfo.getBatSupplierCode();
        String batBatch = gaiaBatchInfo.getBatBatch();
        String batBatchNo = gaiaBatchInfo.getBatBatchNo();
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getSupplierCode, batSupplierCode));
        if (Objects.isNull(supplier)) {
            log.info("供应商有问题supplier={}", JSON.toJSONString(supplier));
            return;
        }
//        List<TestSetGoods> testSetGoods = testSetGoodsService.list(Wrappers.<TestSetGoods>lambdaQuery().eq(TestSetGoods::getTestSetId, testSetId));
        List<TestSetStore> testSetStores = testSetStoreService.list(Wrappers.<TestSetStore>lambdaQuery().eq(TestSetStore::getTestSetId, testSetId));
        List<String> storeIdList = testSetStores.stream().map(TestSetStore::getStoreId).collect(Collectors.toList());
        List<Store> stores = storeService.listByIds(storeIdList);

        if (Objects.isNull(gaiaProductBusiness)) {
            log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
            return;
        }
        List<SaleStock> saleStockList = Lists.newArrayList();
        //门店发货
        int[] random = random(num, testSet.getDeliverNum(), stores.size());
        //乱序 再打乱一遍
        Collections.shuffle(stores);
        //剔除掉没有进货价的
//        goods = goods.stream().filter(r -> Objects.nonNull(r.getPrice())).collect(Collectors.toList());
        for (int i = 0; i < random.length; i++) {
            Store store = stores.get(i);
            //随机到的货物数量
            int goodsNum = random[i];
            //没随机到货就不发了
            if (goodsNum == 0) {
                continue;
            }
            String poId = randomPdNo(wmCjrq);
            String billNo = SaleStockTypeEnum.randomBillNo(SaleStockTypeEnum.PD, wmCjrq);


            //门店发货数据
            SaleStock saleStock = new SaleStock();
            saleStock.setSaleType(1);
            saleStock.setType("store");
            saleStock.setTest(1);
            saleStock.setNum(goodsNum);
            saleStock.setStoCode(store.getStoreCode());
            saleStock.setSupplierId(supplier.getSupplierId());
//            saleStock.setPoId();
//            saleStock.setBillNo();
//            saleStock.setPayName("聚合付");
            saleStock.setFactoryName(gaiaProductBusiness.getProFactoryName());
//            saleStock.setAmountReceivable(gaiaProductBusiness.getPrice().multiply(new BigDecimal(sellNum)));
            saleStock.setCanRebate(0);
            saleStock.setBatchNo(wmPch);
            saleStock.setBatch(batBatchNo);
//                P20221001476
            saleStock.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
            saleStock.setGoodsId(goods.getGoodsId());
            saleStock.setPoId(poId);
            saleStock.setBillNo(billNo);
//                saleStock.setSupplierId();
//SD2308131W4K4WI9ZHS6
//            saleStock.setGssdBillNo("SD2308131W4K4WI9ZHS6");
            saleStock.setAmountReceivable(price.multiply(new BigDecimal(goodsNum)));
            saleStock.setReceivablePrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setOriginalPrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setPrice(price);
            saleStockList.add(saleStock);

            //连锁发货数据
            SaleStock saleStockBatch = new SaleStock();
            saleStockBatch.setSaleType(1);
            saleStockBatch.setType("store");
            saleStockBatch.setTest(1);
            saleStockBatch.setNum(goodsNum);
            saleStockBatch.setStoCode("100");
            saleStockBatch.setBillNo(billNo);
//            saleStockBatch.setPoId();
//            saleStock.setPayName("聚合付");
            saleStockBatch.setFactoryName(gaiaProductBusiness.getProFactoryName());
//            saleStock.setAmountReceivable(gaiaProductBusiness.getPrice().multiply(new BigDecimal(sellNum)));
            saleStockBatch.setCanRebate(0);
            saleStockBatch.setBatchNo(wmPch);
            saleStockBatch.setSupplierId(supplier.getSupplierId());
            saleStockBatch.setBatch(batBatchNo);
//                P20221001476
            saleStockBatch.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
            saleStockBatch.setGoodsId(goods.getGoodsId());
//                saleStock.setSupplierId();
//SD2308131W4K4WI9ZHS6
//            saleStock.setGssdBillNo("SD2308131W4K4WI9ZHS6");
            saleStockBatch.setPrice(price);
            saleStockBatch.setPoId(poId);
            saleStockBatch.setAmountReceivable(price.multiply(new BigDecimal(goodsNum)));
            saleStockBatch.setReceivablePrice(saleStockBatch.getAmountReceivable().doubleValue());
            saleStockBatch.setOriginalPrice(saleStockBatch.getAmountReceivable().doubleValue());
            saleStockList.add(saleStockBatch);


            //生成商品销售数据 最大拆成100单售卖
            int[] randomGoods = random(goodsNum, testSet.getSellNum(), 100);

            for (int gIndex = 0; gIndex < randomGoods.length; gIndex++) {
                int sellNum = randomGoods[gIndex];
                if (sellNum == 0) {
                    continue;
                }

                SaleStock saleStockSale = new SaleStock();
                saleStockSale.setSaleType(1);
                saleStockSale.setType("sale");
                saleStockSale.setTest(1);
                saleStockSale.setNum(sellNum);
                saleStockSale.setStoCode(store.getStoreCode());
                saleStockSale.setPayName("聚合付");
                saleStockSale.setFactoryName(goods.getVender());
                saleStockSale.setAmountReceivable(price.multiply(new BigDecimal(sellNum)));
                saleStockSale.setCanRebate(0);
                saleStockSale.setBatchNo(wmPch);
                saleStockSale.setBatch(batBatchNo);
//                P20221001476
                saleStockSale.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
                saleStockSale.setGoodsId(goods.getGoodsId());
                saleStockSale.setSupplierId(supplier.getSupplierId());
//SD2308131W4K4WI9ZHS6
                saleStockSale.setGssdBillNo(randomBillNo(wmCjrq));
                saleStockSale.setPrice(price);
//                saleStock.setSalerId(r.getGssdSalerId());
//                saleStock.setSalerName(r.getBatSalesmanName());
//                saleStock.setCashier(r.getGssdSalerId());

                if (Objects.nonNull(gaiaProductBusiness)) {
                    saleStockSale.setProductionEnterprise(gaiaProductBusiness.getProFactoryName());
                    saleStockSale.setHolder(gaiaProductBusiness.getProHolder());
                }
                saleStockSale.setReceivablePrice(saleStockSale.getAmountReceivable().doubleValue());
                saleStockSale.setOriginalPrice(saleStockSale.getAmountReceivable().doubleValue());
                saleStockList.add(saleStockSale);
            }
        }
        log.info("[生成测试数据],生成的测试数据 saleStockList={}", JSON.toJSONString(saleStockList));
        saleStockService.saveBatch(saleStockList);
    }


    /**
     * 生成测试数据 版本2 需要发货数据
     *
     * @param testSet
     */
    public void generateSingleTestDataV2(TestSet testSet, String proCode, Integer num, String wmPch, String wmCjrq) {
        if (Objects.equals(num, 0)) {
            return;
        }
        String testSetId = testSet.getTestSetId();

        GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessService.getOne(Wrappers.<GaiaProductBusiness>lambdaQuery().eq(GaiaProductBusiness::getProSelfCode, proCode));
        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, proCode));
        if (Objects.isNull(goods)) {
            log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
            return;
        }
        BigDecimal price = null;
        Double proHyj = gaiaProductBusiness.getProHyj();
        if (Objects.nonNull(proHyj)) {
            price = BigDecimal.valueOf(proHyj);
        } else {
            price = new BigDecimal(0);
        }

        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery()
                .eq(GaiaBatchInfo::getBatBatch, wmPch));
        if (Objects.isNull(gaiaBatchInfo)) {
            log.info("批次数据有问题gaiaBatchInfo={}", JSON.toJSONString(gaiaBatchInfo));
            return;
        }
        String batSupplierCode = gaiaBatchInfo.getBatSupplierCode();
        String batBatchNo = gaiaBatchInfo.getBatBatchNo();
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getSupplierCode, batSupplierCode));
        if (Objects.isNull(supplier)) {
            log.info("供应商有问题supplier={}", JSON.toJSONString(supplier));
            return;
        }
//        List<TestSetGoods> testSetGoods = testSetGoodsService.list(Wrappers.<TestSetGoods>lambdaQuery().eq(TestSetGoods::getTestSetId, testSetId));
        List<TestSetStore> testSetStores = testSetStoreService.list(Wrappers.<TestSetStore>lambdaQuery().eq(TestSetStore::getTestSetId, testSetId));
        List<String> storeIdList = testSetStores.stream().map(TestSetStore::getStoreId).collect(Collectors.toList());
        List<Store> stores = storeService.listByIds(storeIdList);

        if (Objects.isNull(gaiaProductBusiness)) {
            log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
            return;
        }
        List<SaleStock> saleStockList = Lists.newArrayList();
        //门店发货
        int[] random = random(num, testSet.getDeliverNum(), stores.size());
        //乱序 再打乱一遍
        Collections.shuffle(stores);
        //剔除掉没有进货价的
//        goods = goods.stream().filter(r -> Objects.nonNull(r.getPrice())).collect(Collectors.toList());
        for (int i = 0; i < random.length; i++) {
            Store store = stores.get(i);
            //随机到的货物数量
            int goodsNum = random[i];
            //没随机到货就不发了
            if (goodsNum == 0) {
                continue;
            }
            String poId = randomPdNo(wmCjrq);
            String billNo = SaleStockTypeEnum.randomBillNo(SaleStockTypeEnum.PD, wmCjrq);

            //门店发货数据
            SaleStock saleStock = new SaleStock();
            saleStock.setSaleType(1);
            saleStock.setType("store");
            saleStock.setTest(1);
            saleStock.setNum(goodsNum);
            saleStock.setBillNo(billNo);
            saleStock.setStoCode(store.getStoreCode());
            saleStock.setSupplierId(supplier.getSupplierId());
//            saleStock.setPayName("聚合付");
            saleStock.setFactoryName(gaiaProductBusiness.getProFactoryName());
//            saleStock.setAmountReceivable(gaiaProductBusiness.getPrice().multiply(new BigDecimal(sellNum)));
            saleStock.setCanRebate(0);
            saleStock.setBatchNo(wmPch);
            saleStock.setBatch(batBatchNo);
//                P20221001476
            saleStock.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
            saleStock.setGoodsId(goods.getGoodsId());
            saleStock.setPoId(poId);
//                saleStock.setSupplierId();
//SD2308131W4K4WI9ZHS6
//            saleStock.setGssdBillNo("SD2308131W4K4WI9ZHS6");
            saleStock.setAmountReceivable(price.multiply(new BigDecimal(goodsNum)));
            saleStock.setReceivablePrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setOriginalPrice(saleStock.getAmountReceivable().doubleValue());
            saleStock.setPrice(price);
            saleStockList.add(saleStock);

            //连锁发货数据
            SaleStock saleStockBatch = new SaleStock();
            saleStockBatch.setSaleType(1);
            saleStockBatch.setType("store");
            saleStockBatch.setTest(1);
            saleStockBatch.setNum(goodsNum);
            saleStockBatch.setBillNo(billNo);
            saleStockBatch.setBatch(batBatchNo);
            saleStockBatch.setStoCode("100");
//            saleStock.setPayName("聚合付");
            saleStockBatch.setFactoryName(gaiaProductBusiness.getProFactoryName());
//            saleStock.setAmountReceivable(gaiaProductBusiness.getPrice().multiply(new BigDecimal(sellNum)));
            saleStockBatch.setCanRebate(0);
            saleStockBatch.setBatchNo(wmPch);
            saleStockBatch.setSupplierId(supplier.getSupplierId());
//                P20221001476
            saleStockBatch.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
            saleStockBatch.setGoodsId(goods.getGoodsId());
//                saleStock.setSupplierId();
//SD2308131W4K4WI9ZHS6
//            saleStock.setGssdBillNo("SD2308131W4K4WI9ZHS6");
            saleStockBatch.setPrice(price);
            saleStockBatch.setPoId(poId);
            saleStockBatch.setAmountReceivable(price.multiply(new BigDecimal(goodsNum)));
            saleStockBatch.setReceivablePrice(saleStockBatch.getAmountReceivable().doubleValue());
            saleStockBatch.setOriginalPrice(saleStockBatch.getAmountReceivable().doubleValue());
            saleStockList.add(saleStockBatch);
            WholesaleSalesRecordBatch wholesaleSalesRecordBatch = new WholesaleSalesRecordBatch();
            wholesaleSalesRecordBatch.setBatchNo(saleStockBatch.getBatchNo());
            wholesaleSalesRecordBatch.setUsedNum(0);
            // 20盒三天内销售完 100盒7天内销售完
            if (goodsNum < 20) {
                wholesaleSalesRecordBatch.setEndTime(saleStockBatch.getSaleTime() + 1000 * 60 * 60 * 24 * 3);
            } else {
                wholesaleSalesRecordBatch.setEndTime(saleStockBatch.getSaleTime() + 1000 * 60 * 60 * 24 * 7);
            }
            wholesaleSalesRecordBatch.setDeliverId(poId);
            wholesaleSalesRecordBatch.setProCode(goods.getCommodityCode());
            wholesaleSalesRecordBatch.setTotalNum(goodsNum);
            wholesaleSalesRecordBatch.setStoreCode(store.getStoreCode());
            wholesaleSalesRecordBatchService.save(wholesaleSalesRecordBatch);
//            //生成商品销售数据 最大拆成100单售卖
//            int[] randomGoods = random(goodsNum, testSet.getSellNum(), 100);
//
//            for (int gIndex = 0; gIndex < randomGoods.length; gIndex++) {
//                int sellNum = randomGoods[gIndex];
//                if (sellNum == 0) {
//                    continue;
//                }
//
//                SaleStock saleStockSale = new SaleStock();
//                saleStockSale.setSaleType(1);
//                saleStockSale.setType("sale");
//                saleStockSale.setTest(1);
//                saleStockSale.setNum(sellNum);
//                saleStockSale.setStoCode(store.getStoreCode());
//                saleStockSale.setPayName("聚合付");
//                saleStockSale.setFactoryName(goods.getVender());
//                saleStockSale.setAmountReceivable(price.multiply(new BigDecimal(sellNum)));
//                saleStockSale.setCanRebate(0);
//                saleStockSale.setBatchNo(wmPch);
////                P20221001476
//                saleStockSale.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), wmCjrq));
//                saleStockSale.setGoodsId(goods.getGoodsId());
//                saleStockSale.setSupplierId(supplier.getSupplierId());
////SD2308131W4K4WI9ZHS6
//                saleStockSale.setGssdBillNo(randomBillNo(wmCjrq));
//                saleStockSale.setPrice(price);
////                saleStock.setSalerId(r.getGssdSalerId());
////                saleStock.setSalerName(r.getBatSalesmanName());
////                saleStock.setCashier(r.getGssdSalerId());
//
//                if (Objects.nonNull(gaiaProductBusiness)) {
//                    saleStockSale.setProductionEnterprise(gaiaProductBusiness.getProFactoryName());
//                    saleStockSale.setHolder(gaiaProductBusiness.getProHolder());
//                }
//                saleStockSale.setReceivablePrice(saleStockSale.getAmountReceivable().doubleValue());
//                saleStockSale.setOriginalPrice(saleStockSale.getAmountReceivable().doubleValue());
//                saleStockList.add(saleStockSale);
//            }
        }
        log.info("[生成测试数据],生成的测试数据 saleStockList={}", JSON.toJSONString(saleStockList));
        saleStockService.saveBatch(saleStockList);
    }

    public void generateSale(String time) {
        List<WholesaleSalesRecordBatch> list = wholesaleSalesRecordBatchMapper.findBatchUnused();
        for (WholesaleSalesRecordBatch wholesaleSalesRecord : list) {
            try {
                Integer usedNum = wholesaleSalesRecord.getUsedNum();
                Integer totalNum = wholesaleSalesRecord.getTotalNum();
                Long endTime = wholesaleSalesRecord.getEndTime();
                usedNum = Objects.isNull(usedNum) ? 0 : usedNum;
                Integer leftNum = totalNum - usedNum;
                long intervalTime = endTime - System.currentTimeMillis();
                //待要生成测试数据的数量
                int calNum = 0;
                //间隔超过一天才要分配
                if (intervalTime >= DAY_TIME) {
                    //还需要处理几天
                    float day = intervalTime / DAY_TIME;
                    //每天要处理的数量 平均数 向下去整
                    calNum = (int) (leftNum / day);
                    //处理完更新使用量
                    wholesaleSalesRecord.setUsedNum(usedNum + calNum);
                } else {
                    //少于一天的就把余量处理完
                    calNum = leftNum;
                    wholesaleSalesRecord.setUsedNum(usedNum + calNum);
                }
                wholesaleSalesRecordBatchMapper.updateById(wholesaleSalesRecord);
                log.info("待更新数据wholesaleSalesRecord ={}", JSON.toJSONString(wholesaleSalesRecord));
                generateSingleSaleData(calNum, wholesaleSalesRecord, time);
//                generateSingleTestData(testSet, wholesaleSalesRecord.getProCode(), calNum, wholesaleSalesRecord.getBatchNo(), timeParam);
            } catch (Exception e) {
                log.error("测试测试数据异常, wholesaleSalesRecord={}，异常={}", JSON.toJSONString(wholesaleSalesRecord), e.getMessage());
                e.printStackTrace();
            }
        }

    }

    /**
     * 生成销售数据
     *
     * @param calNum
     * @param wholesaleSalesRecordBatch
     * @param time
     */
    public void generateSingleSaleData(Integer calNum, WholesaleSalesRecordBatch wholesaleSalesRecordBatch, String time) {
        generateSingleSaleData(calNum, wholesaleSalesRecordBatch.getProCode(), wholesaleSalesRecordBatch.getStoreCode(), wholesaleSalesRecordBatch.getBatchNo(), time, null);
    }

    public void generateSingleSaleData(Integer calNum, String proCode, String storeCode, String batchNo, String time, String tag) {
        if (calNum <= 0) {
            return;
        }
        GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessService.getOne(Wrappers.<GaiaProductBusiness>lambdaQuery().eq(GaiaProductBusiness::getProSelfCode, proCode));
        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, proCode));
        if (Objects.isNull(goods)) {
            log.info("商品数据有问题goods={}", JSON.toJSONString(proCode));
            return;
        }
        BigDecimal price = null;
        Double proHyj = gaiaProductBusiness.getProHyj();
        if (Objects.nonNull(proHyj)) {
            price = BigDecimal.valueOf(proHyj);
        } else {
            price = new BigDecimal(0);
        }

        Store store = storeService.getOne(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, storeCode));
        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery()
                .eq(GaiaBatchInfo::getBatBatch, batchNo));
        if (Objects.isNull(gaiaBatchInfo)) {
            log.info("批次数据有问题gaiaBatchInfo={}", JSON.toJSONString(gaiaBatchInfo));
            return;
        }
        String batSupplierCode = gaiaBatchInfo.getBatSupplierCode();
        String batBatch = gaiaBatchInfo.getBatBatch();
        String batBatchNo = gaiaBatchInfo.getBatBatchNo();
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getSupplierCode, batSupplierCode));
        if (Objects.isNull(supplier)) {
            log.info("供应商有问题supplier={}", JSON.toJSONString(supplier));
            return;
        }

        SaleStock saleStockSale = new SaleStock();
        saleStockSale.setSaleType(1);
        saleStockSale.setType("sale");
        saleStockSale.setTest(1);
        saleStockSale.setNum(calNum);
        saleStockSale.setTag(tag);
        saleStockSale.setStoCode(storeCode);
        saleStockSale.setPayName("聚合付");
        saleStockSale.setFactoryName(goods.getVender());
        saleStockSale.setAmountReceivable(price.multiply(new BigDecimal(calNum)));
        saleStockSale.setCanRebate(0);
        saleStockSale.setBatchNo(batchNo);
//                P20221001476
        saleStockSale.setSaleTime(getRandomTime(store.getOpenDate(), store.getCloseDate(), time));
        saleStockSale.setGoodsId(goods.getGoodsId());
        saleStockSale.setSupplierId(supplier.getSupplierId());
//SD2308131W4K4WI9ZHS6
        saleStockSale.setGssdBillNo(randomBillNo(time));
        saleStockSale.setPrice(price);
        String billNo = SaleStockTypeEnum.randomBillNo(SaleStockTypeEnum.LS, time);
        saleStockSale.setBillNo(billNo);
        saleStockSale.setPoId(billNo);
//        saleStockSale.setBatch();
//                saleStock.setSalerId(r.getGssdSalerId());
//                saleStock.setSalerName(r.getBatSalesmanName());
//                saleStock.setCashier(r.getGssdSalerId());

        saleStockSale.setReceivablePrice(saleStockSale.getAmountReceivable().doubleValue());
        saleStockSale.setOriginalPrice(saleStockSale.getAmountReceivable().doubleValue());
        saleStockService.save(saleStockSale);
    }


    private String randomBillNo(String time) {
        return "SD" + time + RandomUtil.randomString(12);
    }

    private String randomPdNo(String time) {
        return "PD" + time + RandomUtil.randomString(12);
    }


    public static int[] random(int total, int fixedRateNum, int storePoolNum) {
        //总份数
        int num = (int) Math.ceil((double) total / fixedRateNum);
        //拆成几份  总份数比门店数量还小按份数，比门店多 按门店数量
        int length = (int) (num < storePoolNum ? num : storePoolNum);
        int[] result = new int[length];

        for (int i = 0, remain = (num - length), residueNum = total - length * fixedRateNum; i < length; i++) {
            if (i == length - 1) {
                result[i] = fixedRateNum + residueNum;
            } else {
                if (remain <= 1) {
                    int time = fixedRateNum * remain;
                    residueNum -= time;
                    remain = 0;
                    result[i] = time + fixedRateNum;
                } else {
                    int nu = RandomUtil.randomInt(1, remain);
                    remain -= nu;
                    residueNum -= nu * fixedRateNum;
                    result[i] = (nu + 1) * fixedRateNum;
                }

            }
        }
        log.info("[生成测试数据],随机数组 result={}", JSON.toJSONString(result));
        return result;
    }

    private static Long getRandomTime(Date openDate, Date closeDate, String wmCjrq) {

        LocalTime localTimeOpen = LocalTime.of(openDate.getHours(), openDate.getMinutes());
        LocalTime localTimeClose = LocalTime.of(closeDate.getHours(), closeDate.getMinutes());
        //昨天
//        LocalDate date = LocalDate.now().minusDays(1);
        LocalDate date = LocalDate.parse(wmCjrq, SIMPLE_DATE_FORMAT1);

        LocalDateTime localDateTime = LocalDateTime.of(date, localTimeOpen);
        long epochSecondOpen = localDateTime.toEpochSecond(ZonedDateTime.now().getOffset());

        LocalDateTime localDateTimeClose = LocalDateTime.of(date, localTimeClose);
        long epochSecondClose = localDateTimeClose.toEpochSecond(ZonedDateTime.now().getOffset());

        return RandomUtil.randomLong(epochSecondOpen, epochSecondClose) * 1000;
    }

//    public static void main(String[] args) {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
//        Long randomTime = null;
//        try {
//            randomTime = getRandomTime(simpleDateFormat.parse("08:30"), simpleDateFormat.parse("20:30"), "20240101");
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
//        System.out.println(randomTime);
//
//    }


}
